package cn.yunhe.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.yunhe.dao.ReplyDao;
import cn.yunhe.entity.Board;
import cn.yunhe.entity.Reply;
import cn.yunhe.entity.Topic;
import cn.yunhe.entity.User;
import cn.yunhe.util.C3P0Util;

public class ReplyDaoImpl implements ReplyDao {

	@Override
	public boolean addReply(Reply reply) {
		int num = -1;
		Connection conn = C3P0Util.getConnection();
		StringBuilder sql = new StringBuilder();
		sql.append(" insert into tb_reply(content,create_time,uid,tid) ");
		sql.append(" values(?,?,?,?.?)");
		PreparedStatement ps = null;
		try {
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql.toString());
			ps.setString(1, reply.getContent());
			ps.setString(2, reply.getCreateTime());
			ps.setInt(3, reply.getUser().getId());
			ps.setInt(4, reply.getTopic().getId());
			ps.setInt(5, reply.getParentId());
			num = ps.executeUpdate();
			conn.commit();
			if (num > 0) {
				return true;
			} else {
				return false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			C3P0Util.close(null, ps, conn);
		}
	}

	@Override
	public List<Reply> findReplyByTopicId(int topicId) {
		List<Reply> rlist = new ArrayList<Reply>();
		Connection conn = C3P0Util.getConnection();
		StringBuilder sql = new StringBuilder();
		sql.append(" select r.rid,r.content,r.create_time,u.uid,u.uname");
		sql.append(" from tb_reply r , tb_user u ");
		sql.append(" where  r.uid = u.uid and r.tid = ?");
		sql.append(" order by create_time asc");
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql.toString());
			ps.setInt(1, topicId);
			rs = ps.executeQuery();
			while (rs.next()) {
				Reply reply = new Reply();
				reply.setId(rs.getInt("rid"));
				reply.setContent(rs.getString("content"));
				reply.setCreateTime(rs.getString("create_time"));
				reply.setUser(new User(rs.getInt("uid"),rs.getString("uname")));
				rlist.add(reply);
			}
			return rlist;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return rlist;
		} finally {
			C3P0Util.close(rs, ps, conn);
		}
	}

}
